extends Control
@onready var grid_container: GridContainer = $GridContainer
@onready var test_7: Node2D = $Node2D
@onready var grid_container_2: GridContainer = $GridContainer2
@onready var timer: Timer = $Timer
@onready var texture_rect: TextureRect = $TextureRect/HSplitContainer/TextureRect
@onready var texture_rect_2: TextureRect = $TextureRect/HSplitContainer/TextureRect2
@onready var h_split_container: HSplitContainer = $TextureRect/HSplitContainer
@onready var fight: Control = $"."
var time = 3
var time_0 = load("res://resource/ui/00C438F80000.png")
var time_1 = load("res://resource/ui/000B29F40000.png")
var time_2 = load("res://resource/ui/CCA124FE0000.png")
var time_3 = load("res://resource/ui/8F1C6C0C0000.png")
var time_4 = load("res://resource/ui/04DAF93C0000.png")
var time_5 = load("res://resource/ui/05F221160000.png")
var time_6 = load("res://resource/ui/6F2478B40000.png")
var time_7 = load("res://resource/ui/193EE9090000.png")
var time_8 = load("res://resource/ui/39A3DE450000.png")
var time_9 = load("res://resource/ui/4E8329060000.png")
#当前执行到第几步
#0进入战斗场景
#1人物选择攻击方式
#2召唤兽选择攻击方式
#3真正的战斗我方开始攻击对方怪物反击
var current_steps: int = 0
var npc_list: Array
var team_list: Array
var userInfo = StringUtil.read_file_to_Dic("res://config/UserInfo.json")
var current_role_position: int = 0
var action_array: Array = []
# 显示最总的攻击动画
var show_array: Array = []
var my_str: String = ""
var unix_timestamp: float = 0
var all_list: Array
signal hide_fight()

var action_team_array: Array = []


func init_data(json_npc: String):
	var _temp_json = '[{"id":1,"tag":1,"position":0,"skin":10900,"name":"鬼王68","fullHp":36,"fullMp":69,"fullAp":43,"fullSp":68,"currentHp":36,"currentMp":69,"currentAp":43,"currentSp":68},{"id":2,"tag":1,"position":1,"skin":10900,"name":"鬼王86","fullHp":55,"fullMp":13,"fullAp":27,"fullSp":86,"currentHp":55,"currentMp":13,"currentAp":27,"currentSp":86},{"id":3,"tag":1,"position":2,"skin":10900,"name":"鬼王74","fullHp":76,"fullMp":83,"fullAp":65,"fullSp":74,"currentHp":76,"currentMp":83,"currentAp":65,"currentSp":74},{"id":4,"tag":1,"position":3,"skin":10900,"name":"鬼王47","fullHp":38,"fullMp":57,"fullAp":10,"fullSp":47,"currentHp":38,"currentMp":57,"currentAp":10,"currentSp":47},{"id":5,"tag":1,"position":4,"skin":10900,"name":"鬼王21","fullHp":49,"fullMp":76,"fullAp":80,"fullSp":21,"currentHp":49,"currentMp":76,"currentAp":80,"currentSp":21},{"id":6,"tag":1,"position":5,"skin":10900,"name":"鬼王50","fullHp":17,"fullMp":78,"fullAp":22,"fullSp":50,"currentHp":17,"currentMp":78,"currentAp":22,"currentSp":50},{"id":7,"tag":1,"position":6,"skin":10900,"name":"鬼王23","fullHp":56,"fullMp":22,"fullAp":41,"fullSp":23,"currentHp":56,"currentMp":22,"currentAp":41,"currentSp":23},{"id":8,"tag":1,"position":7,"skin":10900,"name":"鬼王55","fullHp":46,"fullMp":58,"fullAp":15,"fullSp":55,"currentHp":46,"currentMp":58,"currentAp":15,"currentSp":55},{"id":9,"tag":1,"position":8,"skin":10900,"name":"鬼王46","fullHp":91,"fullMp":80,"fullAp":86,"fullSp":46,"currentHp":91,"currentMp":80,"currentAp":86,"currentSp":46},{"id":10,"tag":1,"position":9,"skin":10900,"name":"鬼王15","fullHp":95,"fullMp":17,"fullAp":77,"fullSp":15,"currentHp":95,"currentMp":17,"currentAp":77,"currentSp":15},{"id":11,"tag":1,"position":10,"skin":10900,"name":"鬼王34","fullHp":37,"fullMp":10,"fullAp":23,"fullSp":34,"currentHp":37,"currentMp":10,"currentAp":23,"currentSp":34},{"id":12,"tag":1,"position":11,"skin":10900,"name":"鬼王17","fullHp":27,"fullMp":66,"fullAp":76,"fullSp":17,"currentHp":27,"currentMp":66,"currentAp":76,"currentSp":17},{"id":13,"tag":1,"position":12,"skin":10900,"name":"鬼王35","fullHp":10,"fullMp":55,"fullAp":57,"fullSp":35,"currentHp":10,"currentMp":55,"currentAp":57,"currentSp":35},{"id":14,"tag":1,"position":13,"skin":10900,"name":"鬼王17","fullHp":10,"fullMp":32,"fullAp":80,"fullSp":17,"currentHp":10,"currentMp":32,"currentAp":80,"currentSp":17},{"id":15,"tag":1,"position":14,"skin":10900,"name":"鬼王43","fullHp":45,"fullMp":64,"fullAp":42,"fullSp":43,"currentHp":45,"currentMp":64,"currentAp":42,"currentSp":43},{"id":16,"tag":1,"position":15,"skin":10900,"name":"鬼王42","fullHp":72,"fullMp":62,"fullAp":76,"fullSp":42,"currentHp":72,"currentMp":62,"currentAp":76,"currentSp":42},{"id":17,"tag":1,"position":16,"skin":10900,"name":"鬼王17","fullHp":23,"fullMp":62,"fullAp":86,"fullSp":17,"currentHp":23,"currentMp":62,"currentAp":86,"currentSp":17},{"id":18,"tag":1,"position":17,"skin":10900,"name":"鬼王45","fullHp":88,"fullMp":10,"fullAp":91,"fullSp":45,"currentHp":88,"currentMp":10,"currentAp":91,"currentSp":45},{"id":19,"tag":1,"position":18,"skin":10900,"name":"鬼王91","fullHp":87,"fullMp":11,"fullAp":46,"fullSp":91,"currentHp":87,"currentMp":11,"currentAp":46,"currentSp":91},{"id":20,"tag":1,"position":19,"skin":10900,"name":"鬼王70","fullHp":39,"fullMp":22,"fullAp":37,"fullSp":70,"currentHp":39,"currentMp":22,"currentAp":37,"currentSp":70}]'
	var json_data_npc = JSON.new()
	json_data_npc.parse(_temp_json)
	for i in json_data_npc.get_data():
		all_list.append(i)
	for i in all_list.size():
		var right_1: Node = preload("res://layout/test8.tscn").instantiate()
		right_1.position = get_location(all_list[i]['position'])
		test_7.add_child(right_1)
		right_1.connect("click_npc", Callable(self, "_on_click_npc"))
		right_1.connect("my_ttttt", Callable(self, "_on_my_ttttt"))
		all_list[i]["node"] = right_1
		if i < 10:
			right_1.set_stand("res://animation/test1.tres", "guard_7", all_list[i]['name'], all_list[i]['position'])
		else:
			right_1.set_stand("res://animation/test1.tres", "guard_3", all_list[i]['name'], all_list[i]['position'])
	current_role_position = 17
	timer.start()

func _ready() -> void:
	pass

func get_dic_aa(position: float) -> Dictionary:
	var _abc: Dictionary
	for i in all_list.size():
		if all_list[i]['position'] == position:
			_abc = all_list[i]
	return _abc

func _physics_process(delta: float) -> void:
	if not show_array.is_empty():
		var _show_data = show_array[0]
		if -1 == _show_data['tag']:
			action_array.clear()
			show_array.clear()
			current_steps = 0
			if get_right_array(all_list).size() == 0 or get_left_array(all_list).size() == 0:
				emit_signal("hide_fight")
			else:
				time = 3
				timer.wait_time = 1
				timer.start()
				h_split_container.visible = true
				grid_container.visible = true
		else:
			var _gongjizhe = get_dic_aa(_show_data['attack_position'])
			var _zaoshougongjizhe = get_dic_aa(_show_data['under_attack_position'])
			if 1 == _show_data['tag']:
				_gongjizhe["node"].position = _gongjizhe["node"].position.move_toward(_show_data['end_position'], 30)
				if _gongjizhe["node"].position == _show_data['end_position']:
					show_array.remove_at(0)
			elif 2 == _show_data['tag']:
				if _show_data['is_start']:
					_show_data['is_start'] = false
					_gongjizhe["node"].set_physical_attack("res://animation/test1.tres", _show_data['attack_animation_name'], _gongjizhe['name'], _show_data['attack_position'])
					_zaoshougongjizhe["node"].set_under_attack("res://animation/test1.tres", _show_data['under_attack_animation_name'], _zaoshougongjizhe['name'], _show_data['attack_position'], _show_data['damage_value'])
			elif 3 == _show_data['tag']:
				_gongjizhe["node"].set_stand("res://animation/test1.tres", _show_data['attack_animation_name'], _gongjizhe['name'], _gongjizhe["position"])
				_zaoshougongjizhe["node"].set_stand("res://animation/test1.tres", _show_data['under_attack_animation_name'], _zaoshougongjizhe['name'], _zaoshougongjizhe["position"])
				_gongjizhe["node"].position = _gongjizhe["node"].position.move_toward(_show_data['initial_position'], 30)
				if _gongjizhe["node"].position == _show_data['initial_position']:
					show_array.remove_at(0)
	else:
		pass

##获取位置
func get_location(index: float) -> Vector2:
	if index >= 15:
		return Vector2(340 + 580 - ((index - 15) * 60), ((index - 15) * 100) + 80 + 160)
	elif index >= 10:
		return Vector2(340 + 480 - ((index - 10) * 60), ((index - 10) * 100) + 40 + 160)
	elif index >= 5:
		return Vector2(340 + 100 - ((index - 5) * 60), ((index - 5) * 100) + 40 + 160)
	else:
		return Vector2(340 - (index * 60), (index * 100) + 160)

##npc的点击事件
func _on_click_npc(info: Vector2, size: Vector2, position: int):
	if show_array.is_empty():
		#当前执行到第几步
#0进入战斗场景
#1人物选择攻击方式
#2召唤兽选择攻击方式
#3真正的战斗我方开始攻击对方怪物反击
		if current_steps == 0:
			# 进入战斗场景显示任务操作列表,如果人物跟召唤兽都死了,则显示不全的操作列表,否则显示完整的列表
			var _role = get_data_for_aa(all_list, current_role_position)
			var _pet = get_data_for_aa(all_list, current_role_position - 5)
			if _role['currentHp'] <= 0 and (_pet.is_empty() or _pet['currentHp'] <= 0):
				# 人物跟召唤兽都死了,则显示不全的操作列表
				pass
			else:
				# 显示完整的操作列表
				# 如果召唤兽死了则直接
				current_steps = 1
				grid_container.visible = false
				grid_container_2.visible = true
				action_team_array.append({"tag": 1, "attack_position": current_role_position, "under_attack_position": position})
		elif current_steps == 1:
			#1人物选择攻击方式
			current_steps = 2
			grid_container_2.visible = false
			h_split_container.visible = false
			timer.stop()
			action_team_array.append({"tag": 1, "attack_position": current_role_position - 5, "under_attack_position": position})
			npc_random_attack()

func _on_my_ttttt(position: int):
	if not show_array.is_empty():
		var _show_data = show_array[0]
		var _gongjizhe = get_dic_aa(_show_data['attack_position'])
		var _zaoshougongjizhe = get_dic_aa(_show_data['under_attack_position'])
		if 2 == _show_data['tag']:
			if not _show_data['is_start']:
				show_array.remove_at(0)


func _on_texture_button_pressed() -> void:
	print("点击了人物 法术")
	current_steps = 1

func _on_texture_button_2_pressed() -> void:
	print("点击了人物 道具")
	current_steps = 1

func _on_texture_button_3_pressed() -> void:
	print("点击了人物 防御")
	current_steps = 1

func _on_texture_button_4_pressed() -> void:
	print("点击了人物 保护")
	current_steps = 1

func _on_texture_button_5_pressed() -> void:
	print("点击了人物 召唤")
	current_steps = 1

func _on_texture_button_6_pressed() -> void:
	print("点击了人物 召回")
	current_steps = 1

func _on_texture_button_7_pressed() -> void:
	print("点击了人物 捕捉")
	current_steps = 1

func _on_texture_button_8_pressed() -> void:
	print("点击了人物 逃跑")
	current_steps = 1

func _on_texture_button_9_pressed() -> void:
	print("点击了人物 自动")
	current_steps = 1

func _on_texture_button_pressed2() -> void:
	print("点击了召唤兽 法术")
	current_steps = 2

func _on_texture_button_2_pressed2() -> void:
	print("点击了召唤兽 道具")
	current_steps = 2

func _on_texture_button_3_pressed2() -> void:
	print("点击了召唤兽 防御")
	current_steps = 2

func _on_texture_button_4_pressed2() -> void:
	print("点击了召唤兽 保护")
	current_steps = 2

func _on_timer_timeout() -> void:
	time -= 1
	var number_as_string = str(time)
	if time == 0:
		timer.stop()
		set_show_time(texture_rect, 0)
		set_show_time(texture_rect_2, 0)
		h_split_container.visible = false
		grid_container.visible = false
		grid_container_2.visible = false
		current_steps = 2
		# 敌人随机对队伍进行攻击
		npc_random_attack()
	elif time > 9:
		var first = number_as_string.substr(0, 1)
		set_show_time(texture_rect, int(first))
		var second = number_as_string.substr(1)
		set_show_time(texture_rect_2, int(second))
	else:
		set_show_time(texture_rect, 0)
		set_show_time(texture_rect_2, int(number_as_string))


func get_next_action() -> Dictionary:
	# 第一步从敌人和队友的数组中找出敏最高的活着的单位
	var json_string = JSON.stringify(npc_list)
	npc_list.sort_custom(func(a, b): return a["currentSp"] > b["currentSp"])
	team_list.sort_custom(func(a, b): return a["currentSp"] > b["currentSp"])
	var aaa: Dictionary
	if npc_list[0]['currentSp'] > team_list[0]['currentSp']:
		aaa = npc_list[0]
	else:
		aaa = team_list[0]
	return aaa

func get_left_array(data: Array) -> Array:
	var _abc = []
	for i in data.size():
		if data[i]['position'] < 10 and data[i]['currentHp'] > 0:
			_abc.append(data[i])
	return _abc

func get_right_array(data: Array) -> Array:
	var _abc = []
	for i in data.size():
		if data[i]['position'] > 9 and data[i]['currentHp'] > 0:
			_abc.append(data[i])
	return _abc

func get_data_for_aa(data: Array, position: int) -> Dictionary:
	var _temp_data: Dictionary
	for i in data:
		if i['position'] == position:
			_temp_data = i
	return _temp_data

func get_team_for_position(position: int) -> Dictionary:
	var _temp_data: Dictionary
	for i in action_team_array:
		if i['attack_position'] == position:
			_temp_data = i
	return _temp_data


func npc_random_attack() -> void:
	var _abc = all_list.duplicate(true)
	_abc.sort_custom(func(a, b): return a["currentSp"] > b["currentSp"])
	for i in _abc.size():
		var _gongjizhe = _abc[i]
		if _gongjizhe['currentHp'] > 0:
			if _gongjizhe['position'] < 10:
				#是怪攻击队伍
				if get_right_array(_abc).size() == 0:
					break
				var _right: Dictionary
				var _temp_action = get_team_for_position(_gongjizhe['position'])
				if _temp_action.is_empty():
					_right = get_right_array(_abc).pick_random()
				else:
					var aa = get_data_for_aa(_abc, _temp_action['under_attack_position'])
					if aa.is_empty() or aa['currentHp'] <= 0:
						_right = get_right_array(_abc).pick_random()
					else:
						_right = aa
				action_array.append({"tag": 1, "attack_position": _gongjizhe['position'], "under_attack_position": _right['position']})
				var zuizhong = _right['currentHp'] - _gongjizhe['currentAp']
				if zuizhong > 0:
					_right['currentHp'] = zuizhong
				else:
					_right['currentHp'] = 0
			else:
				if get_left_array(_abc).size() == 0:
					break
				var _left: Dictionary
				var _temp_action = get_team_for_position(_gongjizhe['position'])
				if _temp_action.is_empty():
					_left = get_left_array(_abc).pick_random()
				else:
					var aa = get_data_for_aa(_abc, _temp_action['under_attack_position'])
					if aa.is_empty() or aa['currentHp'] <= 0:
						_left = get_left_array(_abc).pick_random()
					else:
						_left = aa
				action_array.append({"tag": 1, "attack_position": _gongjizhe['position'], "under_attack_position": _left['position']})
				var zuizhong = _left['currentHp'] - _gongjizhe['currentAp']
				if zuizhong > 0:
					_left['currentHp'] = zuizhong
				else:
					_left['currentHp'] = 0
	for i in action_array:
		var _attack_data = get_data_for_aa(all_list, i['attack_position'])
		var _under_attack = get_data_for_aa(all_list, i['under_attack_position'])
		if _attack_data['position'] < 10 and _under_attack['position'] > 9:
			show_array.append({"tag": 1, "attack_position": _attack_data['position'], "under_attack_position": _under_attack['position'], "end_position": _under_attack["node"].position - Vector2(50, 20)})
			show_array.append({"tag": 2, "attack_position": _attack_data['position'], "under_attack_position": _under_attack['position'], "damage_value": '-' + str(int(_attack_data['currentAp'])), "attack_animation_name": "attack_7", "under_attack_animation_name": "hit_3", "is_start": true})
			var zuizhong = _under_attack['currentHp'] - _attack_data['currentAp']
			if zuizhong > 0:
				_under_attack['currentHp'] = zuizhong
				show_array.append({"tag": 3, "attack_position": _attack_data['position'], "under_attack_position": _under_attack['position'], "attack_animation_name": "guard_7", "under_attack_animation_name": "guard_3", 'initial_position': get_location(_attack_data['position'])})
			else:
				_under_attack['currentHp'] = 0
				show_array.append({"tag": 3, "attack_position": _attack_data['position'], "under_attack_position": _under_attack['position'], "attack_animation_name": "guard_7", "under_attack_animation_name": "die_3", 'initial_position': get_location(_attack_data['position'])})
		elif _attack_data['position'] > 9 and _under_attack['position'] < 10:
			show_array.append({"tag": 1, "attack_position": _attack_data['position'], "under_attack_position": _under_attack['position'], "end_position": _under_attack["node"].position + Vector2(50, 20)})
			show_array.append({"tag": 2, "attack_position": _attack_data['position'], "under_attack_position": _under_attack['position'], "damage_value": '-' + str(int(_attack_data['currentAp'])), "attack_animation_name": "attack_3", "under_attack_animation_name": "hit_7", "is_start": true})
			var zuizhong = _under_attack['currentHp'] - _attack_data['currentAp']
			if zuizhong > 0:
				_under_attack['currentHp'] = zuizhong
				show_array.append({"tag": 3, "attack_position": _attack_data['position'], "under_attack_position": _under_attack['position'], "attack_animation_name": "guard_3", "under_attack_animation_name": "guard_7", 'initial_position': get_location(_attack_data['position'])})
			else:
				_under_attack['currentHp'] = 0
				show_array.append({"tag": 3, "attack_position": _attack_data['position'], "under_attack_position": _under_attack['position'], "attack_animation_name": "guard_3", "under_attack_animation_name": "die_7", 'initial_position': get_location(_attack_data['position'])})
	show_array.append({"tag": - 1})
	action_team_array.clear()
	current_steps = 3
	

## 为顶部计时器设置时间
##
## @param texture_rect: TextureRect 节点
## @param number: int 要显示的数字
func set_show_time(texture_rect: TextureRect, number: int) -> void:
	if number == 1:
		texture_rect.texture = time_1
	elif number == 2:
		texture_rect.texture = time_2
	elif number == 3:
		texture_rect.texture = time_3
	elif number == 4:
		texture_rect.texture = time_4
	elif number == 5:
		texture_rect.texture = time_5
	elif number == 6:
		texture_rect.texture = time_6
	elif number == 7:
		texture_rect.texture = time_7
	elif number == 8:
		texture_rect.texture = time_8
	elif number == 9:
		texture_rect.texture = time_9
	else:
		texture_rect.texture = time_0
